package com.kehutong.admin.util;


import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.coraframework.util.Objects;
import org.coraframework.util.UUIDGenerator;


public class CookieUtils extends org.coraframework.authz.util.CookieUtils {

    /**
     * 设置Cookie值，随机生成一个Cookie
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    public static String setCookie(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String cookieValue = UUIDGenerator.randomUUID();
        setCookie(request, response, cookieValue);
        return cookieValue;
    }

    /**
     * 获取Cookie，如果为空则设置Cookie，并返回Cookie值
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    public static String getCookieValueIfNullThenSetCookie(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String cookieValue = getCookieValue(request);
        if (Objects.isEmpty(cookieValue)) {
            cookieValue = setCookie(request, response);
        }
        return cookieValue;
    }

    public static String getAuthToken(HttpServletRequest request) {
        // 从Head中获取token，如果取不到则从session中取
        // 有些方法比如下载文件的时候不能在head中设置token，所以暂时将token存到session中
        String token = request.getHeader("authorization");
        if (Objects.isEmpty(token)) {
            token = getAuthTokenFromSession(request);
        }
        return token;
    }

    public static String getAuthTokenFromSession(HttpServletRequest request) {
        return (String) request.getSession().getAttribute("token");
    }

    public static void overWriteJSessionId(HttpServletRequest request, HttpServletResponse response) {
        try {
            String JSESSIONID = "JSESSIONID";
            String jSessionId = CookieUtils.getCookieValue(request, JSESSIONID);
            if (Objects.nonEmpty(jSessionId)) {
                CookieUtils.setCookie(request, response, JSESSIONID, jSessionId);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}